//
//  RYDizhiViewController.swift
//  SheYangBigData
//
//  Created by 宋海胜 on 2020/12/31.
//  Copyright © 2020 叁拾叁. All rights reserved.
//

import UIKit
import MJRefresh
import RxSwift
import RxDataSources
import Then
import SDCycleScrollView

class RYDizhiViewController: SYBaseTableViewController {
    
    fileprivate var vm: VGTableViewPageViewModel<RYAddressListModel>!
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setRightNavItem()
        setTableView()
        setNoDataView()
        setupViewModel()
        self.title = "我的收货地址"
    }
    
    /*
     {
     "id"
     "appUserId":22,
     "name":"范文涛",
     "mobile":"17867817454",
     "isDefault":0
     "provinceName":"江苏省",
     "cityName":"南京市",
     "districtName":"江宁区",
     "streetName":"禄口街道",
     "address":"",
     "provinceId":20942094041088,
     "cityId":20969856139264,
     "districtId":20971449974784,
     "streetId":20971768741888,
     }
     */
    func editData(_ dic: [String: String]) {
        requestVM.baseRequest(disposeBag: dispose, type: .editAddress(dic: dic), modelClass: SGBaseModel<RYAddressListModel>.self) {[weak self] (res) in
            if let `self` = self {
                self.getList()
            }
            
        } Error: {
            
        }
        
    }
    
    func deleteAddress(_ id: Int) {
        requestVM.baseRequest(disposeBag: dispose, type: .deleteAddress(id: id), modelClass: SGBaseModel<RYKuaidiModel>.self) {[weak self] (res) in
            if let `self` = self {
                self.getList()
            }
            
        } Error: {
            
        }
        
    }
    
    fileprivate func setupViewModel() {
        vm = VGTableViewPageViewModel<RYAddressListModel>()
        vm.tableView = tableView
        vm.emptyViewParams = ("", "", 40.0, 30.0)
        tableView.vg_pageProtocol = vm
        getList()
        vm.getDataClosure = {[weak self] page in
            if let `self` = self {
                self.vm.getList(type: .addressList(page: self.vm.vg_pageNo, size:self.vm.size), dispose: self.dispose)
            }
        }
        vm.loadDataClosure = {[weak self] success in
            if let `self` = self {
                if success {
                    self.loadDataSuccessed()
                }
            }
        }
    }
    
    func getList() {
        vm.getList(type: .addressList(page: 1, size:1000), dispose: dispose)
    }
    
    func loadDataSuccessed() {
        DispatchQueue.main.async {
            
            self.setDataSource()
        }
    }
    
    func setRightNavItem() {
        let item: UIBarButtonItem = UIBarButtonItem(title: "添加", style: UIBarButtonItem.Style.plain, target: self, action: #selector(rightAction))
        self.navigationItem.rightBarButtonItem=item
    }
    
    func setTableView() {
        
        //创建表格视图
        self.tableView = UITableView(frame: CGRect(x: 0, y: NAV_HEIGHT, width: SCREEN_WIDTH, height: SCREEN_HEIGHT-NAV_HEIGHT-BOTTOM_SAFE_HEIGHT), style:.plain)
        self.tableView.separatorStyle = .none
        self.tableView.backgroundColor = UIColor(hex: 0xF2F2F2)
        self.tableView!.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
        self.view.addSubview(self.tableView!)
        
        tableView.rx.itemSelected
            .subscribe(onNext:{ [weak self] indexPath in
                if let `self` = self {
                    self.popVC()
                    self.passParamsClosure?(self.vm.dataSource[indexPath.row])
                }
            })
            .disposed(by:dispose)
    }
    
    func setNoDataView() {
        noDataView = SYNoDataView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT-NAV_HEIGHT))
        noDataView.isHidden = true
        tableView.addSubview(noDataView)
    }
    
    func setDataSource() {
        //初始化数据
        let sections = Observable.just([
            RYAddressListSection(header: "", items: self.vm.dataSource)
        ])
        
        //创建数据源
        let dataSource = RxTableViewSectionedAnimatedDataSource<RYAddressListSection>(
            //设置单元格
            configureCell: { ds, tv, ip, item in
                
                let cell: RYDizhiCell = tv.dequeueReusableCell(withIdentifier: "Cell")
                    as? RYDizhiCell ?? RYDizhiCell(style: .default, reuseIdentifier: "Cell")
                cell.selectionStyle = .none
                cell.currentVC = self
                cell.configureView(item)
                return cell
                
                
            },
            //设置分区头标题
            titleForHeaderInSection: { ds, index in
                return ds.sectionModels[index].header
            })
        tableView.dataSource = nil
        //绑定单元格数据
        sections
            .bind(to: tableView.rx.items(dataSource: dataSource))
            .disposed(by: dispose)
        
    }
    
    @objc func rightAction() {
        let vc = RYAddDizhiViewController()
        vc.backClosure = {[weak self] index in
            if let `self` = self {
                self.getList()
            }
        }
        self.navigationController?.pushViewController(vc, animated: true)
    }
}


//自定义Section
struct RYAddressListSection {
    var header: String
    var items: [Item]
}

extension RYAddressListSection : AnimatableSectionModelType {
    typealias Item = RYAddressListModel
    
    var identity: String {
        return header
    }
    
    init(original: RYAddressListSection, items: [Item]) {
        self = original
        self.items = items
    }
}

extension RYAddressListModel: IdentifiableType {
    var identity: String {
        return id!
    }
    
    typealias Identity = String
}
